import React from 'react';
import { Toast,Picker,List  } from 'antd-mobile'
import { connect } from 'react-redux';
import UEditor from '../component/UEditor';
import _ from 'lodash';
import axios from 'axios';

import 	Api from '../common/ApiConfig';
import { postCommitContent, getCheckPersonal } from '../common/service';
import { saveData } from '../action/UserAction';
import { IMG_UPLOAD_URL } from '../common/systemParam';

import NoPowerShow from '../component/NoPowerShow'



class ConstructionInput extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			textEquipment: [{value:{id:1,name:'锤子'},label:'锤子'}], //可选设备数组
			carNum: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.vehicleNum.toString() : '0',	//车辆数量
			personalNum: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.personNum.toString() : '0',	//人员数量
			equipmentArr: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.deviceIds : [], //选择设备，数量数组
			cantConstruction: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.isconstruct : true,   //是否无法施工
			cantConstructionReason: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.remark : '',//无法施工原因
			constructionPlanEdit: false, //施工计划编辑状态
			constructionCarEdit: false,  //施工计划车辆编辑状态
			constructionPeopleEdit: false,  //施工计划人员编辑状态
			defaultPick: {id: '', name: '请选择设备'}, //选择设备的默认提示
			equipmentNum: '', //填写的设备数量
			constructionText: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.constructionContent[0].content : '', //施工计划文档
			planId: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.planId : null,// 流程id
			constructionTextArr: this.props.userReducer.step.planInfoRes ? this.props.userReducer.step.planInfoRes.constructionContent : []
		}
	}

	componentDidMount() {
		// setTimeout(() => {
		//   global.ue.setContent('<p>new text</p>', true);
		// }, 2000)
		
	}

	changeEditStatu(type) {
		const {carNum, personalNum, constructionCarEdit, constructionPeopleEdit} = this.state;
		if (type === 'car') {
			if (constructionCarEdit && carNum.length > 0 &&  !/^\+?[0-9][0-9]*$/.test(carNum.trim())) {
				Toast.info('请输入有效数字', 2);
				return;
			}
			this.setState({constructionCarEdit: !this.state.constructionCarEdit})
		}else if (type === 'personal') {
			if (constructionPeopleEdit && personalNum.length > 0 &&  !/^\+?[0-9][0-9]*$/.test(personalNum.trim())) {
				Toast.info('请输入有效数字', 2);
				return;
			}
			this.setState({constructionPeopleEdit: !this.state.constructionPeopleEdit})
		}
	}
	//判断字段是否为空
	completeForm() {
		const {textEquipment, carNum, personalNum, equipmentArr, cantConstruction,cantConstructionReason,constructionPlanEdit,constructionPeopleEdit,defaultPick,equipmentNum,constructionText} = this.state;
		return (carNum.trim().length === 0 || personalNum.trim().length === 0 || constructionText.trim().length === 0) 
	}
	//保存
	commit() {
		const {textEquipment, carNum, personalNum, equipmentArr, cantConstruction,cantConstructionReason,constructionCarEdit,
			constructionPlanEdit,constructionPeopleEdit,defaultPick,equipmentNum,constructionText} = this.state;
		if (!cantConstruction && cantConstructionReason.trim().length === 0) {
			Toast.info('无法施工原因不能为空', 2);
			return;
		}
		if (cantConstruction &&constructionCarEdit) {
			Toast.info('请保存车辆数量', 2);
			return;
		}
		if (cantConstruction &&constructionPeopleEdit) {
			Toast.info('请保存人员数量', 2);
			return;
		}
		if (cantConstruction &&carNum.trim().length === 0) {
			Toast.info('车辆数量不能为空', 2);
			return;
		}
		if (cantConstruction &&personalNum.trim().length === 0) {
			Toast.info('人员数量不能为空', 2);
			return;
		}
		let text = '';
		if (cantConstruction && !this.getCurrentStatu(5)) {
			 text = global.ue.getContent();
			if (cantConstruction && text.length === 0) {
				Toast.info('施工计划文档不能为空', 2);
				return;
			}
			this.setState({
				constructionText: text
			});
		}		

		const { showLoadModal, hideLoadModal } = this.props;
		const constructionContent = _.cloneDeep(this.props.userReducer.step.planInfoRes.constructionContent)
		const obj = constructionContent[0];
		obj.content = text.length > 0 ? text : this.state.constructionText;
		constructionContent[0] = obj;
		showLoadModal();
		postCommitContent({
			deviceIds: this.state.equipmentArr,  //设备数组
			flowId: this.props.userReducer.flowId,  //流程Id
			personNum: this.state.personalNum, //人员数量
			vehicleNum: this.state.carNum,
			planId: this.state.planId,
			constructionContent: constructionContent,
			isconstruct: this.state.cantConstruction ? 1 : 0,
			remark: this.state.cantConstructionReason
		})
		.then((data) => {
			hideLoadModal();
			const isOK = data.data;
			if (isOK.success) {
				if (isOK.obj) {
					this.props.dispatch(saveData(isOK.obj));
					this.props.currentPage(isOK.obj.flowBaseInfo.flowProcesses);
					this.setState({constructionPlanEdit: false});
				} else {
					Toast.info('节点已过不可修改', 2);
				}
			} else {
				Toast.info(isOK.msg, 2);
			}
		})
		.catch((e) => {
			hideLoadModal();
			console.log(e);
			Toast.info('服务器异常', 2);
		})
	}
	checkEquire() {
		this.props.showLoadModal();
		getCheckPersonal(this.props.userReducer.flowId)
			.then((data) => {
				this.props.hideLoadModal();
				const isOK = data.data;
				if (isOK.success) {
					this.props.dispatch(saveData(isOK.obj));
					this.props.currentPage(isOK.obj.flowBaseInfo.flowProcesses);
				} else {
					Toast.info(isOK.msg, 2);
				}
			})
			.catch((e) => {
				this.props.hideLoadModal();
				console.log(e);
				Toast.info('服务器异常', 2);
			})
	}
	//获取对应节点的id
	getCurrentId(flowId) {
		const stepArr = this.props.userReducer.step.flowBaseInfo ? this.props.userReducer.step.flowBaseInfo.flowProcesses : [];
		let id = 0;
		for (const obj of stepArr) {
			if (obj.flowId === flowId) {
				id = obj.id;
				break;
			}
		}
		return id;
	}
	//判断当前节点状态
	getCurrentStatu(flowId) {
		const stepArr = this.props.userReducer.step.flowBaseInfo ? this.props.userReducer.step.flowBaseInfo.flowProcesses : [];
		let flag = false;
		for (const obj of stepArr) {
			if (obj.flowId === flowId) {
				if (obj.state === 1) {
					flag = true;
				} else {
					flag = false;
				}
				break;
			}
		}
		return flag;
	}
	//上传图片
	uploadImage() {

		const imgDoc = document.getElementById('fileUpload');
		if (imgDoc.files.length === 0 ) {
			return;
		}
		const file = imgDoc.files[0];
		const imageType = /^image\//;
		if (!imageType.test(file.type)) {
			Toast.info('图片格式不正确', 2);
			return;
		}
		let fd = new FormData();
		fd.append('file', file);
		axios({
          url: Api.uploadImage,
          method: 'post',
          data: fd, 
          headers: { 'Content-Type': 'multipart/form-data',
          'x-access-token': global.token }
        }).then(response => {
          let isOk = response.data;
          console.log(response.data);
          if(isOk.result) {
          	global.ue.setContent(`<img src='${IMG_UPLOAD_URL}${isOk.obj}'><br/><br/>`, true);
          } else {
          	Toast.info('上传图片失败');
          }
        }, response => {
        	console.log(response),
        	Toast.info('服务器异常，上传图片失败');
        })
    imgDoc.value='';
	}
	render() {
		if (this.props.currentObj.id <= this.getCurrentId(13) || this.getCurrentStatu(8) || 
			(-1 === this.props.userReducer.roles.findIndex((value) => value === 54))) {
			return (<NoPowerShow id={this.props.currentObj.flowId}></NoPowerShow>);
		}
		//施工计划确认页面
		const {textEquipment, carNum, personalNum, equipmentArr, cantConstruction,cantConstructionReason,constructionPlanEdit,constructionPeopleEdit,defaultPick,equipmentNum,constructionText} = this.state;
		if (!this.state.constructionPlanEdit) {
			return (
				<div style={{padding: '1.42rem 0.2rem 0.4rem 0.2rem'}}>
					{/* 如果无法施工显示的内容不同 */}
					{this.state.cantConstruction ?
					<div>
						<span className='num-title'>车辆数量</span>
						<span style={{fontSize: '0.32rem',color: '#0e8dea'}}>{carNum}</span>
						<span className='equipment-title'>设备</span>
						{equipmentArr.map((data, index) => {
							return (
								<div style={{paddingLeft: '0.15rem', marginBottom: '0.2rem'}} key={index}>
									<span style={{fontSize: '0.32rem',marginRight:'0.4rem', color: '#ccc'}}>{data.commonName}</span>
									<span style={{fontSize: '0.32rem',color: '#0e8dea', width:'30vw'}}>{data.commonNum}</span>
								</div>
							);
						})}
						<div style={{marginTop: '0.54rem'}}>
							<span className='num-title'>人员数量</span>
							<span style={{fontSize: '0.32rem',color: '#0e8dea'}}>{personalNum}</span>
						</div>
						{ !this.getCurrentStatu(5) ?
							<div style={{marginTop: '0.8rem'}}>
								<p className='num-title' style={{marginBottom: '0.32rem'}}>施工计划文档</p>
								<UEditor id="content" height="200" toolbars={[]} disabled={true} value={this.state.constructionText}/>  

							</div> : null
						}
					</div> : 
						<div>
							<div style={{display:'flex',flexDirection:'row',alignItems:'center'}}>
								<span	style={{fontSize: '0.32rem',fontWeight: 'bold'}}>
									无法施工
								</span>
							</div>
							<div className='cantConstruction'>
								<span style={{fontSize:'0.32rem'}}>原因</span>
								<p className='construction-plan-document'>{this.state.cantConstructionReason}</p>
							</div>
						</div>
					}
					{ -1 === this.props.userReducer.roles.findIndex((value) => value === 56) || !this.props.isTodayStep() ? null :
						<div className='btnCommitConstruction'>
							<div 
								id='inputEditBtns'
								className='btnEdit'
								style={{width: '100%',marginRight:'0rem'}}
								onTouchStart={()=>{document.getElementById('inputEditBtns').style.backgroundColor = '#B7B9B9'}}
								onTouchEnd={()=>{document.getElementById('inputEditBtns').style.backgroundColor = '#ccc'}}
								onClick={() => this.setState({constructionPlanEdit: true, editEd: true})}
							>
								编辑
							</div>
						</div> 
					}
				</div>
			);
		} 
		//施工计划编辑页面
		return (
			<div style={{padding: '1.42rem 0.2rem 0.8rem 0.2rem'}}>
				{ !this.getCurrentStatu(5) ?
					<div style={{display:'flex',flexDirection:'row',alignItems:'center',marginBottom:'0.76rem'}}>
						<div className='check-box-construction'
							onClick={() => this.setState({cantConstruction:!this.state.cantConstruction})}
						> 
						{!this.state.cantConstruction ? 
							<i className="fa fa-check check-icon"></i> : null
						}
						</div>
						<span 
							style={{fontSize: '0.28rem',fontWeight: 'bold'}}
							onClick={() => this.setState({cantConstruction:!this.state.cantConstruction})}
						>
							无法施工
						</span>
					</div>: null
				}
				{/* 如果无法施工显示的内容不同 */}
				{this.state.cantConstruction ? 
				<div>
					<div className='select-num-div' style={{backgroundColor: '#434A57'}}>
						<div>
							<span style={{fontSize: '0.32rem',marginRight: '0.2rem'}}>车辆数量</span>
							<input type='text' className='num-input' style={{border: `1px solid ${this.state.constructionCarEdit ? '#0e8dea' : '#434A57'}`}}
								disabled={this.state.constructionCarEdit ? false : true}
								value={this.state.carNum}
								onChange={(e)=>this.setState({carNum: e.target.value})}
							/>
						</div>
						<div 
							className='select-btn'
							id='carNumBtn'
							onClick={()=> this.changeEditStatu('car')}
						>
								{ this.state.constructionCarEdit ? 
									'保存' : '编辑'
								}
						</div>
					</div>
					<p style={{fontSize:'0.32rem',marginTop:'0.54rem',marginBottom:'0.3rem'}}>设备选择</p>
					<div style={{marginBottom: '0.36rem'}}>
						{this.state.equipmentArr.map((data, index)=> {
							return (
								<div key={index} style={{height:'0.72rem',backgroundColor:'#bababa',display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom: '0.16rem'}}>
									<div style={{display:'flex', marginLeft: '0.12rem'}}>
										<span style={{fontSize:'0.32rem',color:'#333',marginRight:'0.4rem',maxWidth:'45vw',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{data.commonName}</span>
										<span style={{fontSize:'0.32rem',color:'#0e8dea'}}>{data.commonNum}</span>
									</div>
									<div
										style={{backgroundColor:'#909090', borderRadius: '0px',height:'0.72rem', width: '0.72rem',display:'flex',justifyContent:'center',alignItems:'center'}}
										onClick={() => {
											const equipmentArrArr = this.state.equipmentArr;
											equipmentArrArr.splice(index,1);
											this.setState({equipmentArr: equipmentArrArr});
										}}
									>
										<i className='fa fa-trash-o' style={{color:'#7F0000'}}></i>
									</div>
								</div>
							);
						})}
					</div>
					<div style={{display:'flex'}}>
						<div className='equipmentPicker' style={{position:'relative',color: '#666'}}>
							<Picker ref='picker' data={this.props.userReducer.equipment} cols={1} extra={this.state.defaultPick.name}
								onOk={(data) => {
									if (data && data.length === 1)
									 this.setState({defaultPick: data[0]})
								}}
							>
			          <List.Item arrow="horizontal"></List.Item>
			        </Picker>
						</div>
						<input type='text' style={{fontSize: '0.27rem'}} className='numEquipmentInput' placeholder='数量'
						 onChange={(e)=>{this.setState({equipmentNum: e.target.value})}}
						 value={this.state.equipmentNum}
						 maxLength={11}
						/>
						<div
							style={{height:'0.72rem',backgroundColor:'#d9d9d9',borderRadius:'0px',flex: 1,display:'flex',justifyContent:'center',alignItems:'center',lineHeight:'0.72rem',color: '#666',fontSize:'0.24rem',fontWeight:'bold'}}
							icon={<span className='addIcon'></span>}
							onClick={()=>{
								if (this.state.defaultPick.id === '') {
									Toast.info('请选择设备', 1);
									return;
								}
								if (this.state.equipmentNum.trim() === '') {
									Toast.info('请填写数量', 1);
									return;
								}
								if (!/^\+?[1-9][0-9]*$/.test(this.state.equipmentNum.trim())) {
									Toast.info('请输入有效数字', 2);
									return;
								}
								const equipmentArr = this.state.equipmentArr;
								let flag = false;
								for (let obj of equipmentArr) {
									if (obj.commonId === this.state.defaultPick.id) {
										obj.commonNum = this.state.equipmentNum
										flag = true;
										break;
									}
								}
								if (!flag) {
									equipmentArr.push({
										commonId: this.state.defaultPick.id,
										commonName: this.state.defaultPick.name,
										commonNum: this.state.equipmentNum
									});
								}
								console.log(equipmentArr);
								this.setState({
									equipmentArr: equipmentArr,
									defaultPick: {id: '', name: '请选择设备'},
									equipmentNum: ''
								})
							}}
						>
							添加
						</div>
					</div>
					<div className='select-num-div' style={{marginTop:'0.76rem'}}>
						<div>
							<span style={{fontSize: '0.32rem',marginRight: '0.2rem'}}>人员数量</span>
							<input type='text' className='num-input' style={{border: `1px solid ${this.state.constructionPeopleEdit ? '#0e8dea' : '#434A57'}`}}
								disabled={this.state.constructionPeopleEdit ? false : true}
								value={this.state.personalNum}
								onChange={(e)=>this.setState({personalNum: e.target.value})}
							/>
						</div>
						<div 
							className='select-btn'
							id='personalNumBtn'
							onClick={()=> this.changeEditStatu('personal')}
						>
								{ this.state.constructionPeopleEdit ? 
									'保存' : '编辑'
								}
						</div>
					</div>
					{!this.getCurrentStatu(5) ?
						<div className='cantConstruction' style={{position:'relative'}}>
							<span style={{fontSize:'0.32rem', marginBottom: '0.3rem'}}>施工计划文档</span>
							<UEditor  id="contentText" height="200" toolbars={['insertimage', 'insertorderedlist','|','fullscreen']} value={this.state.constructionText}/>
							<input id='fileUpload' type='file' accept="image/*" className='file' style={{display: 'none'}} onChange={this.uploadImage.bind(this)}/> 
							<div style={{width:'0.4rem',height:'0.8rem',backgroundColor:'transparent',position:'absolute',top:'0.4rem',zIndex:'10000000',left:'0.12rem'}}
								onClick={()=>{
									document.getElementById('fileUpload').click();
								}}
							></div> 
						</div> : null
					}
				</div>
				: 
				<div className='cantConstruction'>
					<span style={{fontSize:'0.32rem'}}>原因</span>
					<textarea 
					 className='cantConstructionInput' 
					 placeholder='请输入...'
					 value={this.state.cantConstructionReason}
					 onChange={(e)=>this.setState({cantConstructionReason: e.target.value})}
					></textarea>
				</div>
			}
				{ -1 === this.props.userReducer.roles.findIndex((value) => value === 56) ? null :
					<div 
						id='comfireBtn'
						className='ConstructionEditBtn'
						onTouchStart={()=>{document.getElementById('comfireBtn').style.backgroundColor = '#D97442'}}
						onTouchEnd={()=>{document.getElementById('comfireBtn').style.backgroundColor = '#FFA24A'}}
						onClick={()=>{
							this.commit()
						}}
						>
						保存
					</div>
				}
			</div>
		);
	}
}


function mapStateToProps(state) {
  const { userReducer } = state;
  return {
    userReducer
  };
}

export default connect(mapStateToProps)(ConstructionInput);